package com.nolon.flange.repository

import android.app.Application
import androidx.lifecycle.LiveData
import com.nolon.flange.AppDatabase
import com.nolon.flange.dao.OrderDao
import com.nolon.flange.dao.ProjectDao
import com.nolon.flange.model.Project

class ProjectRepository(application: Application) {
    private val database: AppDatabase by lazy { AppDatabase.getInstance(application) }

    private val projectDao: ProjectDao by lazy { database.projectDao }
    private val orderDao: OrderDao by lazy { database.orderDao }

    val allProjects: LiveData<List<Project>> by lazy { projectDao.getAll() }

    suspend fun insertProject(project: Project): Long {
        return projectDao.insert(project)
    }

    suspend fun updateProject(project: Project) {
        projectDao.update(project)
    }

    suspend fun deleteProject(project: Project) {
        projectDao.delete(project)
        database.orderDao.deleteOrdersByProjectId(project.id)
    }

    suspend fun getProject(projectId: Int) {
        projectDao.getProject(projectId)
    }

    suspend fun orderCount(projectId: Int): Int {
        return orderDao.countOrderByProjectId(projectId)
    }
}